package uno.rocc.framework.security.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "jwt")
@Data
public class JwtUtil {
    private String key;
    private Long expire;
    private String issuer;

    public String generatorToken(Map<String, Object> claims) {
        long nowMills = System.currentTimeMillis();
        Date now = new Date(nowMills);
        Date expire = new Date(nowMills + this.expire * 1000);
        return Jwts.builder()
                .issuedAt(now)
                .expiration(expire)
                .issuer(issuer)
                .claims(claims)
                .signWith(Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8)))
                .compact();
    }

    public Claims parseToken(String token) {
        return Jwts.parser()
                .verifyWith(Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8)))
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

}
